<template>
  <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        :disabled="mode === 'view'"
    >
      <el-form-item label="活动名称" prop="activityName">
        <el-input v-model="form.activityName" placeholder="请输入活动名称" />
      </el-form-item>

      <el-form-item label="活动类型" prop="activityType">
        <el-select v-model="form.activityType" placeholder="请选择活动类型">
          <el-option label="促销活动" value="促销活动" />
          <el-option label="节日活动" value="节日活动" />
          <el-option label="主题活动" value="主题活动" />
        </el-select>
      </el-form-item>

      <el-form-item label="活动周期" prop="activityPeriod">
        <el-date-picker
            v-model="form.activityPeriod"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="适用范围" prop="applicableScope">
        <el-select
            v-model="form.applicableScope"
            multiple
            filterable
            placeholder="请选择适用站点"
            style="width: 100%"
        >
          <el-option
              v-for="station in stationOptions"
              :key="station.id"
              :label="station.stationName"
              :value="station.id"
          >
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span>{{ station.stationName }}</span>
              <span style="color: #8492a6; font-size: 13px">
                {{ station.stationType ? `(${station.stationType})` : '' }}
              </span>
            </div>
            <div style="font-size: 12px; color: #909399">
              {{ station.address }}
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="关联优惠券" prop="relatedToCoupons">
        <el-switch
            v-model="form.relatedToCoupons"
            :active-value="1"
            :inactive-value="0"
        />
      </el-form-item>

      <el-form-item label="活动状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="进行中" value="进行中" />
          <el-option label="已结束" value="已结束" />
          <el-option label="注销" value="注销" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" v-if="mode !== 'view'">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  modelValue: Boolean,
  mode: {
    type: String,
    default: 'add'
  },
  activityData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'refresh'])

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref(null)
const stationOptions = ref([])

const form = ref({
  id: null,
  activityName: '',
  activityType: '',
  activityPeriod: [],
  applicableScope: [],
  relatedToCoupons: 0,
  status: '进行中'
})

// 表单校验规则
const rules = {
  activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  activityPeriod: [{ required: true, message: '请选择活动周期', trigger: 'change' }],
  applicableScope: [{ required: true, message: '请选择适用范围', trigger: 'change' }],
  status: [{ required: true, message: '请选择活动状态', trigger: 'change' }]
}

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    add: '新增活动',
    edit: '修改活动',
    view: '查看活动'
  }
  return titles[props.mode]
})

// 获取站点列表
const fetchStations = async () => {
  try {
    const res = await axios.get('/activityInfo/getAvailableStations', {
      params: {
        stationName: '',  // 可选的站点名称筛选
        stationType: ''   // 可选的站点类型筛选
      }
    })
    if (res.data) {
      stationOptions.value = res.data
    }
  } catch (error) {
    console.error('获取站点列表失败：', error)
    ElMessage.error('获取站点列表失败：' + (error.response?.data?.message || error.message))
  }
}

// 监听 activityData 变化
watch(
    () => props.activityData,
    (newVal) => {
      if (newVal) {
        form.value = {
          ...newVal,
          activityPeriod: newVal.activityPeriod ? newVal.activityPeriod.split('至') : [],
          applicableScope: newVal.applicableScope ? newVal.applicableScope.split(',').map(Number) : []
        }
      }
    },
    { immediate: true }
)

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 构造提交数据
    const submitData = {
      ...form.value,
      // 确保 id 在编辑模式下存在
      id: props.mode === 'edit' ? form.value.id : undefined,
      // 处理日期范围
      activityPeriod: Array.isArray(form.value.activityPeriod)
          ? form.value.activityPeriod.join('至')
          : form.value.activityPeriod,
      // 处理适用范围
      applicableScope: Array.isArray(form.value.applicableScope)
          ? form.value.applicableScope.join(',')
          : form.value.applicableScope,
      // 确保这些字段存在
      status: form.value.status || '进行中',
      relatedToCoupons: form.value.relatedToCoupons || 0
    }

    console.log('提交的数据：', submitData) // 调试用

    const url = props.mode === 'add' ? '/activityInfo/add' : '/activityInfo/update'
    const method = props.mode === 'add' ? 'post' : 'put'

    const res = await axios[method](url, submitData)

    if (res.data) {
      ElMessage.success(props.mode === 'add' ? '添加成功' : '修改成功')
      handleClose()
      emit('refresh')
    }
  } catch (error) {
    console.error('提交失败：', error)
    console.error('错误响应：', error.response?.data) // 添加更详细的错误日志
    ElMessage.error('提交失败：' + (error.response?.data?.message || error.message))
  }
}

// 关闭弹窗
const handleClose = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}

// 生命周期钩子
onMounted(() => {
  fetchStations()
})
</script>

<style scoped>
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input) {
  width: 100%;
}
</style>